package models

import "time"

type PutForward struct {
	ID int `gorm:"primary_key"`
	UserId int
	Phone string
	Title string
	Name string
	Identity int
	Amount float64
	BankCardNo string
	BankName string
	BankBranch string
	ExpectAt time.Time
	ForwardAt time.Time
	Status int
	Remark string
	CreatedAt time.Time
	UpdatedAt time.Time
}

func (p *PutForward) TableName() string {
	return "put_forward"
}

type PutForwardListResult struct {
	ID int `json:"id"`
	Name string `json:"name"`
	Phone string `json:"phone"`
	Bank string `json:"bank"`
	BankCard string `json:"bank_card"`
	Amount float32 `json:"amount"`
	ExpectAt time.Time `json:"expect_at"`
	Status int `json:"status"`
} 
/**
	申请提现列表
 */
func PutFrowardList(page int, pageSize int, status string, phone string, beginTime string, endTime string) ([]*PutForwardListResult, *Paginator) {
	var result []*PutForwardListResult
	model := DB.Table("put_forward").Select("id,name,phone,bank_name as bank,bank_card_no as bank_card,amount,expect_at,status,created_at")
	if status != ""{
		model = model.Where("status=?", status)
	}
	if phone != "" {
		model = model.Where("phone=?", phone)
	}
	if beginTime != "" {
		model = model.Where("expect_at > ?", beginTime)
	}
	if endTime != "" {
		model = model.Where("expect_at < ?", endTime)
	}

	var count int
	model.Count(&count)
	paginate := NewPage(page, pageSize, count)
	model.Offset(paginate.Offset).Limit(paginate.Limit).Order("created_at desc").Find(&result)
	return result, &paginate
}
/**
	提现
 */
func MakeMoney(id int) error {
	tx := DB.Begin()
	var putForward PutForward
	tx.Model(&PutForward{}).Where("id=?",id).First(&putForward)
	err := tx.Model(&PutForward{}).Where("id=?",id).Updates(map[string]interface{}{
		"status": 1,
		"forward_at": time.Now(),
	}).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	err = tx.Model(&UserBill{}).Create(&UserBill{
		UserId:putForward.UserId,
		Type:0,
		Title:"提现",
		Amount:putForward.Amount,
		CreatedAt:time.Now(),
	}).Error
	if err != nil {
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}